import React, { useCallback, useEffect, useState, useRef } from 'react'
import { DataRundownRender } from './render'
import css from './runtime.less'
export default function ({ env, data, outputs, inputs }) {
  const container = useRef(null)
  const borderRef = useRef(null)
  const renderRef = useRef<DataRundownRender | null>(null)
  useEffect(() => {
    if(!container.current) return
    const render = new DataRundownRender(env.runtime)
    render.setColors([data.color1, data.color2, data.color3, data.color4, data.color5, data.color6, data.color7])
    render.setHoverColor(data.hoverColor)
    render.init(container.current!, borderRef.current!, data.mapStyle)
    renderRef.current = render
    return () => {
      renderRef.current = null
      render.destory()
    }
  }, [])

  // 区域颜色变化
  useEffect(() => {
    renderRef.current?.setColors?.([data.color1, data.color2, data.color3, data.color4, data.color5, data.color6, data.color7])
    renderRef?.current?.render()
  }, [data.color1, data.color2, data.color3, data.color4, data.color5, data.color6, data.color7])
  
  // 鼠标hover的颜色
  useEffect(() => {
    renderRef.current?.setHoverColor?.(data.hoverColor)
  }, [data.hoverColor])
  
  
  useEffect(() => {
    renderRef.current?.setMapStyle?.(data.mapStyle)
  }, [data.mapStyle])

  // 数据变化，数据格式 [{name:string,lnglat: [number,number]}]
  inputs['setData']((val:any, outputRels:any) => {
    renderRef.current?.setData?.(val || [])
    outputRels['onSetDataFinish']();
  });
  return (
    <div ref={borderRef} key="amap_border" className={css.map}>
      <div key="amap_content" ref={container} className={css.container}>
        loading...
      </div>
    </div>
  )
}
